package com.maodou.core.datastore.db.dao

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.maodou.core.datastore.db.table.UserCacheEntry

@Dao
interface UserCacheDao {
    
    /**
     * 获取指定用户的缓存数据
     */
    @Query("SELECT * FROM user_cache_entries WHERE userId = :userId AND `key` = :key LIMIT 1")
    suspend fun get(userId: String, key: String): UserCacheEntry?
    
    /**
     * 插入或更新缓存数据
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun upsert(entry: UserCacheEntry): Long
    
    /**
     * 删除指定用户的特定缓存
     */
    @Query("DELETE FROM user_cache_entries WHERE userId = :userId AND `key` = :key")
    suspend fun delete(userId: String, key: String): Int
    
    /**
     * 清除指定用户的所有缓存数据
     */
    @Query("DELETE FROM user_cache_entries WHERE userId = :userId")
    suspend fun clearUserData(userId: String): Int
    
    /**
     * 清除所有用户的缓存数据
     */
    @Query("DELETE FROM user_cache_entries")
    suspend fun clearAll(): Int
    
    /**
     * 获取指定用户的缓存数量
     */
    @Query("SELECT COUNT(*) FROM user_cache_entries WHERE userId = :userId")
    suspend fun countByUser(userId: String): Int
    
    /**
     * 获取所有缓存数量
     */
    @Query("SELECT COUNT(*) FROM user_cache_entries")
    suspend fun count(): Int
    
    /**
     * 根据前缀获取指定用户的缓存列表
     */
    @Query("SELECT * FROM user_cache_entries WHERE userId = :userId AND `key` LIKE :prefix || '%'")
    suspend fun getByPrefix(userId: String, prefix: String): List<UserCacheEntry>
    
    /**
     * 清理过期的缓存数据
     */
    @Query("DELETE FROM user_cache_entries WHERE ttlSeconds IS NOT NULL AND (updatedAt + ttlSeconds * 1000) < :nowMs")
    suspend fun clearExpired(nowMs: Long = System.currentTimeMillis()): Int
    
    /**
     * 清理指定用户的过期缓存数据
     */
    @Query("DELETE FROM user_cache_entries WHERE userId = :userId AND ttlSeconds IS NOT NULL AND (updatedAt + ttlSeconds * 1000) < :nowMs")
    suspend fun clearUserExpired(userId: String, nowMs: Long = System.currentTimeMillis()): Int
    
    /**
     * 获取所有用户ID列表（用于管理和清理）
     */
    @Query("SELECT DISTINCT userId FROM user_cache_entries")
    suspend fun getAllUserIds(): List<String>
}